package com.tencent.trtc.switchroom;

import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;


import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager2.widget.ViewPager2;

import com.example.basic.TRTCBaseActivity;
import com.tencent.rtmp.ui.TXCloudVideoView;
import com.tencent.trtc.TRTCCloud;
import com.tencent.trtc.TRTCCloudDef;
import com.tencent.trtc.TRTCCloudListener;
import com.tencent.trtc.debug.GenerateTestUserSig;

public class ScrollSwitchRoomActivity extends TRTCBaseActivity {


    PageAdapter mAdapter;
    public String[] mRoomIds;
    private TRTCCloud mTRTCCloud;
    private TRTCCloud mSubCloud;
    private TXCloudVideoView mRemoteVideoView;
    private TXCloudVideoView mSubRemoteVideoView;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_scroll_switch_room);

        //隐藏标题栏
        getSupportActionBar().hide();
        mRoomIds = new String[]{"1231", "1232", "1233"};

        if (checkPermission()) {
            initView();
        }

    }

    @Override
    protected void onPermissionGranted() {
        initView();
    }

    private void initView() {

        mAdapter = new PageAdapter(this, mRoomIds);
        ViewPager2 viewPager = findViewById(R.id.viewPager);
        viewPager.setAdapter(mAdapter);
        //设置viewPager 滑动方向
        viewPager.setOrientation(ViewPager2.ORIENTATION_VERTICAL);
        // Initialize your views here
        mTRTCCloud = TRTCCloud.sharedInstance(getApplicationContext());
        mSubCloud = mTRTCCloud.createSubCloud();
        mTRTCCloud.addListener(mTRTCCloudListener);
        mSubCloud.addListener(mSubCloudListener);
    }


    private TRTCCloudListener mTRTCCloudListener = new TRTCCloudListener() {
        public void onEnterRoom(long result) {
            if (result == 0) {
                // Enter room success
            } else {
                // Enter room failed
            }
        }

        public void onExitRoom(int reason) {
            // Exit room
        }


        @Override
        public void onUserVideoAvailable(String userId, boolean available) {
            super.onUserVideoAvailable(userId, available);
            if (available) {
                mTRTCCloud.startRemoteView(userId, TRTCCloudDef.TRTC_VIDEO_STREAM_TYPE_BIG, mRemoteVideoView);
            } else {
                mTRTCCloud.stopRemoteView(userId, TRTCCloudDef.TRTC_VIDEO_STREAM_TYPE_BIG);
            }
        }

        public void onError(int errCode, String errMsg, Bundle extraInfo) {
            // print Error
            Log.e("ScrollSwitchRoom", "Error: " + errCode + " " + errMsg);


        }

    };


    private TRTCCloudListener mSubCloudListener = new TRTCCloudListener() {
        public void onEnterRoom(long result) {
            if (result == 0) {
                // Enter room success
            } else {
                // Enter room failed
            }
        }

        public void onExitRoom(int reason) {
            // Exit room
        }

        @Override
        public void onUserVideoAvailable(String userId, boolean available) {
            super.onUserVideoAvailable(userId, available);
            if (available) {
                mSubCloud.startRemoteView(userId, TRTCCloudDef.TRTC_VIDEO_STREAM_TYPE_BIG, mSubRemoteVideoView);
            } else {
                mSubCloud.stopRemoteView(userId, TRTCCloudDef.TRTC_VIDEO_STREAM_TYPE_BIG);
            }
        }

    };

    private void exitRoom() {

        mTRTCCloud.stopAllRemoteView();
        mTRTCCloud.exitRoom();
        mTRTCCloud.setListener(null);

        mSubCloud.stopAllRemoteView();
        mSubCloud.exitRoom();
        mSubCloud.setListener(null);
    }


    public class PageAdapter extends RecyclerView.Adapter<PageAdapter.PageViewHolder> {


        private Context context;
        public String[] mRoomIds;


        public PageAdapter(Context context, String[] roomIds) {
            this.context = context;
            this.mRoomIds = roomIds;
        }

        public PageViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

            View view = LayoutInflater.from(context).inflate(R.layout.item_scroll_page, parent, false);
            return new PageViewHolder(view);
        }

        public void onBindViewHolder(@NonNull PageViewHolder holder, int position) {
            Log.d("ScrollSwitchRoom", "onBindViewHolder: " + position);
            TextView textView = holder.itemView.findViewById(R.id.tv_room_number);
            textView.setText(getString(R.string.switchroom_roomid) + ":" + mRoomIds[position]);
            holder.setIndex(position);
        }


        @Override
        public void onViewAttachedToWindow(@NonNull PageViewHolder holder) {
            super.onViewAttachedToWindow(holder);

            TRTCCloudDef.TRTCParams mTRTCParams = new TRTCCloudDef.TRTCParams();
            mTRTCParams.sdkAppId = GenerateTestUserSig.SDKAPPID;
            mTRTCParams.userId = "123";
            mTRTCParams.strRoomId = mRoomIds[holder.getIndex()];
            mTRTCParams.userSig = GenerateTestUserSig.genTestUserSig(mTRTCParams.userId);
            mTRTCParams.role = TRTCCloudDef.TRTCRoleAudience;

            boolean isCurMainRoom = (holder.getIndex() % 2) == 0;
            Log.d("ScrollSwitchRoom", "onViewAttachedToWindow 切换房间 roomId: " + mTRTCParams.strRoomId + "mIsCurMainRoom: " + isCurMainRoom);

            if (isCurMainRoom) {
                mSubRemoteVideoView = holder.itemView.findViewById(R.id.txcvv_main_local);
                mSubCloud.muteAllRemoteAudio(true);
                mSubCloud.enterRoom(mTRTCParams, TRTCCloudDef.TRTC_APP_SCENE_LIVE);
            } else {
                mRemoteVideoView = holder.itemView.findViewById(R.id.txcvv_main_local);
                mTRTCCloud.muteAllRemoteAudio(true);
                mTRTCCloud.enterRoom(mTRTCParams, TRTCCloudDef.TRTC_APP_SCENE_LIVE);
            }


        }

        @Override
        public void onViewDetachedFromWindow(@NonNull PageViewHolder holder) {
            super.onViewDetachedFromWindow(holder);
            Log.d("ScrollSwitchRoom", "onViewDetachedFromWindow: " + holder.toString());

            boolean isCurMainRoom = (holder.getIndex() % 2) == 0;
            if (isCurMainRoom) {
                mSubCloud.exitRoom();
                mTRTCCloud.muteAllRemoteAudio(false);

            } else {
                mTRTCCloud.exitRoom();
                mSubCloud.muteAllRemoteAudio(false);

            }

        }

        public int getItemCount() {
            return mRoomIds.length;
        }

        public int getItemViewType(int position) {
            return position;
        }

        class PageViewHolder extends RecyclerView.ViewHolder {

            public int index = 0;

            PageViewHolder(@NonNull View itemView) {
                super(itemView);
            }

            public void setIndex(int index) {
                this.index = index;
            }

            public int getIndex() {
                return index;
            }
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        exitRoom();
    }

}